import Common
from Common import Logger as Logger
from PlaylistHelperUtil import PlaylistHelper
from UsersDBUtil import UsersDB
from MovieDBUtil import MovieDB

class GetHandler:
    
    def __init__(self, user):
        self.user = user
        self.logger = Common.getLogger
        
        #databases here
        self.usersDB = UsersDB(user)
        self.movPlaylistsDB = MovieDB(self.logger)
        
    def resolve(self, user, name):
        self.logger.logthis("*********************************************", Logger.GET_Request)
        self.logger.logthis("Begin Resolve " + name + " for " + user, Logger.GET_Request)
        fileReturned = None
        
        if Common.strContains(name, ".ts"):
            fileReturned = self.GET_ts(user, name)
        elif Common.strContains(name, ".m3u8"):
            fileReturned = self.GET_m3u8(user, name)
        else:
            fileReturned = None
        
        self.logger.logthis("For "+user+", Resolved "+name+" with "+str(fileReturned), Logger.GET_Request)
        self.logger.logthis("********************************************* \n", Logger.GET_Request)
        return str(fileReturned)
    
    def GET_m3u8(self, user, name):
        self.logger.logthis("*********************************************", Logger.GET_Request)
        self.logger.logthis("BEGIN GET_m3u8 " + name + " for " + user, Logger.GET_Request)
        fileReturned = None
        
        #PS: lastRequest = None => First time user
        lastRequest = self.usersDB.GetLastRequestedItem(user)
        self.logger.logthis("Last requested item was: " + str(lastRequest), Logger.GET_Request)
        
        playList = self.movPlaylistsDB.GetItems(name, lastRequest, 5)
        playList.WriteToStdOut()
        
        self.logger.logthis("END GET_m3u8 " + name + " for " + user, Logger.GET_Request)
        self.logger.logthis("*********************************************", Logger.GET_Request)
        
        return fileReturned
    
    def GET_ts(self, user, name):
        # assumption name is always a part of the m3u8 that was sent
        
        if not Common.FileExists(name):
            Common.errorLogger.write("GET TS: " + name + " \n")
            Common.errorLogger.write(name + ": File Not found " + " \n")
        
        self.logger.logthis("Setting last requested item to: " + name, Logger.GET_Request)
        self.usersDB.SetLastRequestedItem(user, name)
        
        self.logger.logthis("Pushing " + name + " to output", Logger.GET_Request)
        Common.writeHeaderToOutput(name)
        Common.writeFileToStdout(name)
        return name
    
